/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-04-21 23:20:34
 * @FilePath: \plugin-demo\background\background.js
 */

// 需要拦截请求URL
const requestUrl = 'https://www.baidu.com/s';

// 封装好对象，避免代码太多太乱了...（个人习惯）
var webRequest = {
  // 开始监听-初始化
  auto() {
    chrome.webRequest.onCompleted.addListener(
      this.logResponse, {
        urls: ["*://*/*"]
      },
    );
  },

  //监听请求
  logResponse(responseDetails) {
    if (responseDetails.url.includes(requestUrl)) {
      sendMessage.sendMessageToContentScript({
        cmd: 'response',
        data: responseDetails
      });

      // 弹框
      chrome.notifications.create('cakeNotification', {
        "type": "basic",
        "iconUrl": chrome.runtime.getURL("images/logo.png"),
        "title": "Time for cake!",
        "message": "Something something cake"
      });
    }
  },
}

var sendMessage = {
  // 获取当前选项卡ID
  getCurrentTabId(callback) {
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, function (tabs) {
      if (callback) callback(tabs.length ? tabs[0].id : null);
    });
  },

  // 向标签中的content_script发送消息
  sendMessageToContentScript(message, callback) {
    this.getCurrentTabId((tabId) => {
      console.log("tabId:", tabId);
      chrome.tabs.sendMessage(tabId, message, function (response) {
        if (callback) callback(response);
      });
    });
  }
}

webRequest.auto();